var entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    userController = require('../../../User/server/controllers/users.server.controller'),
    BarcodeEnum = require('../../../Barcode/server/controllers/Enum.server.controller'),
    QCEnum = require('../../../QC/server/controllers/Enum.server.controller');

//根据装配条码查找其条码主档信息
exports.findAssemblyBarcodeMaster = function (barcode, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
};
//根据条码查找条码主档
exports.findBarcodeMaster = function (barcode, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({Barcode: barcode}, [
            {path: 'ItemMaster', select: 'Code Name Specification ItemCategory'},
            {path: 'MO', select: 'Code LotNumber Customer StartDateTime EndDateTime'},
            {path: 'Work', select: 'Name'},
            {path: 'BizRecord'},
            {path: 'Operation'},
            {path: 'Users', select: 'Code Name'}
        ],
        function (err, record) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档错误';
                newErr.message = '查询失败，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, record);
            }
        }
    );
};

//根据条码查找条码主档
exports.findBarcodeMasters = function (barcodes, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.find({Barcode: {$in: barcodes}}, {Barcode: 1}, [
            {path: 'Operation', select: 'ConnectArea'}
        ],
        function (err, record) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档错误';
                newErr.message = '查询失败，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, record);
            }
        }
    );
};

//查找不合格条码主档
exports.findBadMasters = function (completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.Entity
    .find({
        BarcodeType: BarcodeEnum.BarcodeType.ItemMaster,
        QCStatus: QCEnum.QCStatus.NotQualified
    }, { Barcode: 1, WorkName: 1, WorkLocationName: 1, Users: 1, MOLotNumber: 1, ItemMasterCode: 1, ItemMasterName: 1})
    .populate({path: 'Users', select: 'Code Name'})
    .exec(function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询条码主档错误';
            newErr.message = '查询失败，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

exports.findUser = function (barcode, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({Barcode: barcode}, null, function (err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询条码主档错误';
            newErr.message = '查询失败，请检查查询参数！';
            completeFun(newErr);
        } else {
            if (record == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档失败';
                newErr.message = '该条码在系统中不存在！';
                completeFun(newErr);
            } else {
                if (record.BarcodeType != BarcodeEnum.BarcodeType.Person) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '查询员工信息失败';
                    newErr.message = '该条码不是员工条码！';
                    completeFun(newErr);
                } else {
                    userController.getUserAndRolesInfo(record.EntityID, function (err, user) {
                        completeFun(err, user);
                    });
                }
            }
        }
    });
};

exports.updateByValue = function (barcode, value, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.updateByValue(barcode, value, function (err, result) {
        completeFun(err, result);
    });
};
/**
 * [findBarcodeMasterByCoditions 根据条件查询条码主档]
 * author jiadx
 * @param  MOLotNumber     [批次（可为空）]
 * @param  completeFun
 * @return {[type]}             [条码主档记录]
 */
exports.findAllBarcodeMaster = function (optNum, completeFun) {
    var entityDepartment = entityCollection.getEntity("WorkLocation");
    //查询工位和部门保存到对象，作为对照表

    entityDepartment.find({}, null, {
        path: 'Department',
        select: 'Code Name'
    }, function (err, records) {
        if (err) {
            completeFun(err);
            return;
        }
        var department = {};
        records.forEach(function (record) {
            if (!department.hasOwnProperty(record._id)) {
                department[record._id] = {
                    workLocation: record._id,
                    departmentCode: record.Department ? record.Department.Code : '',
                    department: record.Department ? record.Department.Name : ''
                };
            }
        });
        //条码主档进行分组
        var entity = entityCollection.getEntity("BarcodeMaster");
        var barcodeMap = function () {
            emit(this.MOLotNumber, {WorkLocations: [this.WorkLocation]});
        };
        var barcodeReduce = function (key, values) {
            var res = {WorkLocations: []};
            values.forEach(function (val) {
                val.WorkLocations.forEach(function (WorkLocation) {
                    res.WorkLocations.push(WorkLocation);
                });
            });
            return res;
        };

        var barcodeQuery = {
            IsComplete: false
        };

        if (optNum != '') {
            barcodeQuery.MOLotNumber = {$in: optNum};
        }

        var option = {
            map: barcodeMap,
            reduce: barcodeReduce,
            sort: {MOLotNumber: -1},
            query: barcodeQuery
        };

        entity.mapReduce(option, function (err, results) {
            if (err) {
                completeFun(err);
                return;
            }
            var lastArr = [];
            for (var i = 0; i < results.length; i++) {
                var lastResult = {
                    MoLotNum: results[i]._id
                };
                for (var j = 0; j < results[i].value.WorkLocations.length; j++) {
                    if (department.hasOwnProperty(results[i].value.WorkLocations[j])) {
                        results[i].value.WorkLocations[j] = department[results[i].value.WorkLocations[j]].department;
                    }
                    if (!lastResult.hasOwnProperty(results[i].value.WorkLocations[j])) {
                        lastResult[results[i].value.WorkLocations[j]] = 0;
                    }
                    if (lastResult.hasOwnProperty(results[i].value.WorkLocations[j])) {
                        lastResult[results[i].value.WorkLocations[j]] += 1;
                    }
                }
                lastArr.push(lastResult);
            }
            completeFun(err, lastArr);
        });
    });
};
